<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserPhoneBindRequest;
use App\Http\Requests\Api\UserRequest;
use App\Http\Resources\UserResource;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use App\Models\User;


class UserController extends Controller
{
    //个人信息
    public function me(Request $request){
        return new UserResource($request->user());
    }

    public function show(UserRequest $request,User $user){
        $this->authorize('show',$user);
        $user = $user->where("id","=",$request->id)->first();
        return new UserResource($user);
    }
    public function bing_phone(UserPhoneBindRequest $request){
        $verficationData = \Cache::get($request->phone_key);
        //如果有微信绑定的话，就带入微信绑定信息
        $wx_info = \Cache::get($request->unionid_key);
        $nickname = $request->nickname;
        if (!$verficationData){
            abort(403,"短信验证码失效");
        }
        if (!hash_equals($verficationData['code'],$request->phone_code)){
            throw new AuthenticationException("验证码错误");
        }
        $phone = $verficationData['phone'];
        //判断这手机之前是否有账号
        $user = User::where("phone",$phone)
                ->first();

        //有账号的话就把微信信息绑定到之前的账号
        if ($user){
//            $user = User::combineUser($user,$request->user());
            if ($wx_info){
                foreach ($wx_info as $key=>$val){
                    $user->$key = $val;
                }
            }
            $user->nickname = $nickname;
            $user->save();
        }else{
            $wx_info['phone'] = $phone;
            $wx_info['come_from'] = $request->come_from?$request->come_from:"";
            $wx_info['nickname'] = $request->nickname;
            $request->age_range? $wx_info['age_range'] = $request->age_range:"";
            $wx_info['register_time'] = time();
            $wx_info['phone_bind'] = true;
            $request->area ? $wx_info['address'] = $request->area:"";
            $request->location_id ? $wx_info['location_id'] =  $request->location_id:""; //???扫码注册的要不要单独开个口
            $request->sex ? $wx_info['sex'] = $request->sex : "";
            $user = User::create($wx_info);
        }
        \Cache::forget($request->unionid_key);
        //微信登录成功，并且有绑定过手机号
        $token = auth('api')->login($user);
        // 重新返回登录态和登录信息
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ])->setStatusCode(201);
    }



    //猜你喜欢
    public function guess_your_favourite(Request $request){
        return $request->user()->favourite_goods();
    }
}
